package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.listener.ExcelListener;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Windows
 * @description 针对表【category(商品分类)】的数据库操作Service实现
 * @createDate 2024-01-30 11:23:20
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {

    @Override
    public List<Category> findByParentId(Long parentId) {
        List<Category> categoryList = this.list(new LambdaQueryWrapper<Category>()
                .eq(parentId != null, Category::getParentId, parentId));

        // 查询其下有无子节点，有的话设置标记
        if (!CollectionUtils.isEmpty(categoryList)) {
            setHasChildrenList(categoryList);
        }

        return categoryList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            // 设置返回类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyExcel没有关系
            String fileName = URLEncoder.encode("分类数据", "UTF-8");
            // 设置响应头，否则不弹出下载的框
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 获取所有分类数据
            List<Category> categoryList = this.list();

            // 将原实体转换成显示用
            List<CategoryExcelVo> categoryExcelVoList = categoryList.stream().map(category -> {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo);
                return categoryExcelVo;
            }).collect(Collectors.toList());

            // 写入excel，使用响应流
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class)
                    .sheet("分类数据").doWrite(categoryExcelVoList);

        } catch (Exception e) {
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Transactional
    @Override
    public void importData(MultipartFile file) {
        try {
            ExcelListener<CategoryExcelVo> excelListener = new ExcelListener<CategoryExcelVo>(this);
            EasyExcel.read(file.getInputStream(), CategoryExcelVo.class, excelListener)
                    .sheet().doRead();
        } catch (IOException e) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }

    /**
     * 设置list中的是否有子节点的信息（优化后，减少数据库压力）
     *
     * @param categoryList
     * @return
     */
    private void setHasChildrenList(List<Category> categoryList) {

        // 当前节点作为父节点查询数据库
        List<Long> parentIdList = categoryList.stream().map(Category::getId).collect(Collectors.toList());

        // 获取每个父节点下有几个子节点
        List<Map<String, Object>> parentIdAndCount = this.listMaps(new LambdaQueryWrapper<Category>()
                .select(Category::getParentId)
                .in(Category::getParentId, parentIdList)
                .groupBy(Category::getParentId)
                .having("count(*) > 0"));

        //    <parentId, count(*)>
        // 将有子节点的parentId放入一个Set中，便于快速查找
        Set<Long> parentIdSet = parentIdAndCount.stream()
                .map(map -> (Long) map.get("parent_id"))
                .collect(Collectors.toSet());

        // 设置hasChildren属性
        categoryList.stream().forEach(category -> category.setHasChildren(parentIdSet.contains(category.getId())));


    }
}




